<?php
/**
 * Access Control List
 * Kriticka cast aplikacie, v ktorej nesmu by logicke chyby
 * @author Tomas Srna
 * @package bakalarka
 */

class Acl extends Singleton
{
	private $data = array();
	
	/**
	 * V konstruktore nacitame zaznamy ktore sa nas tykaju
	 * @param UserModel $user 		Uzivatel pre ktoreho chceme ACL 
	 * 								(default: aktualny)
	 */
	protected function __construct($user = NULL)
	{
		$search = array();
		
		if($user == NULL)
			$user = Auth::instance()->getUser();
		
		// Anonymnemu priradime rolu @anonymous a *
		if($user == NULL)
		{
			$search[] = "*";
			$search[] = "@anonymous";
		}
		// Uzivatelovi priradime user, @group a *
		else
		{
			$search[] = "*";
			$search[] = "@" . $user -> group;
			$search[] = $user -> username;
		}
		
		foreach($search as $s)
		{
			foreach(Selector::select('*')->from(AclModel::struct())
				->where('role = ?', $s)->fetch() as $a)
			{
				$this->data[$a->resource] = $a->allow;
			}
		}
	}
	
	/**
	 * Je zdroj povoleny?
	 * @param string $resource		Zdroj
	 */
	public function allowed($resource)
	{
		// Defaultne nepovolime
		$r = false;
		
		// *
		if(array_key_exists('*', $this->data))
		{
			if($this->data['*'] == 1)
				$r = true;
			if($this->data['*'] == 0)
				$r = false;
		}
		
		// resource
		if(array_key_exists($resource, $this->data))
		{
			if($this->data[$resource] == 1)
				$r = true;
			if($this->data[$resource] == 0)
				$r = false;
		}
		
		//print_r($this->data);
		
		return $r;
	}
}
